package cn.sjlink.config;


import cn.sjlink.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author
 *  该拦截器检测登陆
 */
//@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private RedisUtil redisUtils;

    /**
     * 前置检查
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        System.out.println("token 预定前检查----------------");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }else {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Method method = handlerMethod.getMethod();
            final Class<?> clazz = method.getDeclaringClass();
            if (clazz.isAnnotationPresent(LoginHandler.class) ||
                    method.isAnnotationPresent(LoginHandler.class)) {
                String token = request.getHeader("token");
                if (token != null && !"".equals(token)) {
                    token = "repeat" + token;
                    System.out.println(redisUtils.get(token));
                    return true;
                } else {
                    return true;
                }
            }
        }
        return true;

    }


    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

        System.out.println("token 结束检查----------------");
        String token = httpServletRequest.getHeader("token");
        System.out.println(redisUtils.get("repeat"+token));
        if(token != null && !"".equals(token)) {

            redisUtils.remove("repeat" + token);
        }
    }


}
